package com.ctyun.xstore.vod;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctyun.xstore.vod.video.model.PartETag;

public class SerialPartUploader extends AbstractPartUploader {

	private final Logger log = LoggerFactory.getLogger(SerialPartUploader.class);

	@Override
	protected List<PartETag> doMultiPartupload(File file, List<String> urls, int partSize) throws IOException {
		log.info("Start to multipartUpload serially....");
		try (FileInputStream fin = new FileInputStream(file); FileChannel channel = fin.getChannel()) {
			ByteBuffer buffer = ByteBuffer.allocate(partSize);
			byte[] partContent = new byte[partSize];
			List<PartETag> etags = new ArrayList<>();
			int partIndex = 0;
			int partLength = 0;
			while ((partLength = (channel.read(buffer))) != -1) {
				((Buffer) buffer).flip();
				buffer.get(partContent, 0, partLength);
				String partEtag = this.upload(urls.get(partIndex), partContent, 0, partLength);
				etags.add(new PartETag(partIndex + 1, partEtag));
				((Buffer) buffer).clear();
				partIndex++;
			}
			log.info("MultipartUpload serially has done!");
			return etags;
		}
	}
}
